package daliytool.http.server.support;

import daliytool.WebViewMain;
import daliytool.vo.RootPathVO;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.Properties;

/**
 * 描述 新通教育
 *
 * @author ddshuai
 * @date 2018-10-26 10:48
 **/
public class WebContext {
    private static final Logger logger = LoggerFactory.getLogger(WebContext.class);
    private static String rootPath;
    public static final String CONFIG = "/config.properties";
    public static final String OA = "oa";
    public static final String HR = "hr";

    public static void setRootPath(String rootPath,String sys) {
        String path = System.getProperty("user.dir") + CONFIG;
        String oa = getRootPath(OA);
        String hr = getRootPath(HR);

        File config = new File(path);
        if (!config.exists()) {
            try {
                FileUtils.touch(config);
            } catch (IOException e) {
                logger.error("创建文件异常", e);
            }
        }
        //读取config
        try (InputStream inputStream = new FileInputStream(config);
             OutputStream outputStream = new FileOutputStream(config)) {
            Properties properties = new Properties();
            properties.load(inputStream);
            if (StringUtils.isNotEmpty(oa)){
                properties.setProperty(OA, oa);
            }
            if (StringUtils.isNotEmpty(hr)){
                properties.setProperty(HR, hr);
            }

            properties.setProperty(sys, rootPath);

            properties.store(outputStream, "更新");

        } catch (IOException e) {
            logger.error("读取配置异常", e);
        }
        WebContext.rootPath = rootPath;
    }

    public static String getRootPath(String sys) {
        String path = System.getProperty("user.dir") + CONFIG;
        File file = new File(path);
        if (!file.exists()){
            return "";
        }
        try (InputStream inputStream = new FileInputStream(file)) {
            Properties properties = new Properties();
            properties.load(inputStream);

            return properties.getProperty(sys);
        } catch (IOException e) {
            logger.error("读取配置异常", e);
        }
        return WebContext.rootPath;
    }

    public static RootPathVO getRootPath(){
        return new RootPathVO(getRootPath(OA),getRootPath(HR));
    }

    public static void main(String[] args) {
        WebContext.setRootPath("HR_NI_HOA",HR);
    }
}
